#pragma once
#include "Uniform.h"
#include "GLState.h"
#include "core/CImage.h"

class PbrMaterial {
public:
	PbrMaterial() = default;

	CColor baseColor;
	float metallic, roughness;
	CImage textureImage;

	bool hasTexture() const { return textureImage.isValid(); }

	void setAsUniform(Uniform& uniform, bool isLightEnabled = false) {
		uniform.add("enableLight", isLightEnabled);
		uniform.addStruct("material",
			Field("baseColor", baseColor),
			Field("metallic", metallic),
			Field("roughness", roughness)
		);
		bool _hasTexture = hasTexture();
		uniform.add("isTexImage", _hasTexture);
		if (_hasTexture) {
			Sampler2DArg arg;
			arg.texUnit = m_texUnit;
			arg.name = "textureImg";
			/**
			 *@important avoid multiple times load texture leading to memory overflow!
			 *@note because of never uninstall the loaded texture, must do like this!
			 */
			if (m_texture == 0)
				m_texture = GLState::loadTexture(textureImage, arg.texUnit);
			arg.texture = m_texture;
			uniform.setSampler2D(arg);
		}
	}

	void setTextureUnit(GLuint unit) {
		if (!hasTexture())
			return;
		m_texUnit = unit;
	}

private:
	GLuint m_texUnit = 1;// GL_TEXTURE0 is reserved for default
	GLuint m_texture = 0;// invalid
};